package com.example.androidstart.opengl;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.example.androidstart.R;
import com.example.androidstart.opengl.camera.CameraKit;
import com.example.androidstart.opengl.camera.CameraView;
import com.example.androidstart.util.PermissionUtils;

/**
 * 官方camera使用教程
 * https://developer.android.google.cn/guide/topics/media/camera?hl=en#java
 */
public class CameraActivity extends AppCompatActivity {

    private CameraKit mCamerakit;

    private CameraView mCameraView;

    private int mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;

    private final Runnable mInitViewRunnable = new Runnable() {
        @Override
        public void run() {
            setContentView(R.layout.activity_open_camera);
            ViewGroup viewGroup = findViewById(R.id.camera_preview);
            mCamerakit = new CameraKit();
            Camera camera = mCamerakit.open(mCurrentCameraId);
            setCameraDisplayOrientation(CameraActivity.this, Camera.CameraInfo.CAMERA_FACING_BACK, camera);
            mCameraView = new CameraView(CameraActivity.this, camera);
            FrameLayout.LayoutParams frameLayout = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            viewGroup.addView(mCameraView, frameLayout);
        }
    };

    // https://www.jianshu.com/p/c362c6de0e23
    //https://developer.android.google.cn/reference/android/hardware/Camera.html#setDisplayOrientation(int)
    public void setCameraDisplayOrientation(Activity activity,
                                            int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PermissionUtils.askPermission(this, Manifest.permission.CAMERA, 10, mInitViewRunnable);
        boolean isHasCamera = checkCameraHardware(CameraActivity.this);
        if (!isHasCamera) {
            CameraActivity.this.finish();
        }

    }

    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("切换摄像头").setTitle("切换摄像头").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode == 10, grantResults, mInitViewRunnable,
                new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(CameraActivity.this, "没有获得相机权限", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String name = item.getTitle().toString();
        if (name.equals("切换摄像头")) {
            mCurrentCameraId = mCurrentCameraId == 0 ? 1 : 0;
            mCameraView.switchCamera(CameraActivity.this, mCurrentCameraId);
        }
        return super.onOptionsItemSelected(item);
    }
}